<template>
  <div id="addQuestionPage">
    <div style="max-height: 700px; overflow-y: auto; padding-right: 16px">
      <!-- 标题和应用ID -->
      <div style="margin-bottom: 24px">
        <h2 style="margin-bottom: 16px; font-size: 24px; font-weight: bold">
          设置题目
        </h2>
        <a-form-item label="应用 ID" style="margin-bottom: 24px">
          <span>{{ appId }}</span>
        </a-form-item>
      </div>

      <!-- 添加题目和生成题目按钮 -->
      <a-space
        size="large"
        style="
          margin-bottom: 24px;
          width: 100%;
          display: flex;
          align-items: center;
          justify-content: space-between;
        "
      >
        <a-button type="primary" @click="addQuestion(questionContent.length)">
          向底部添加题目
        </a-button>
        <AiGenterateQuestion
          :appId="appId"
          :onSuccess="onAiGenerateSuccess"
          :onSSESuccess="onAiGenerateSuccessSSE"
          :onSSESatrt="onSSESatrt"
          :onSSEClose="onSSEClose"
        />
      </a-space>

      <!-- 题目列表 -->
      <a-card :style="{ width: '100%', marginTop: '16px' }">
        <div
          v-for="(question, index) in questionContent"
          :key="index"
          style="margin-bottom: 16px"
        >
          <a-space
            size="large"
            style="
              margin-bottom: 16px;
              width: 100%;
              display: flex;
              align-items: center;
              justify-content: space-between;
            "
          >
            <h3>题目 {{ index + 1 }}</h3>
            <div>
              <a-button
                size="small"
                @click="addQuestion(index + 1)"
                style="margin-right: 8px"
              >
                添加题目
              </a-button>
              <a-button
                size="small"
                status="danger"
                @click="deleteQuestion(index)"
              >
                删除题目
              </a-button>
            </div>
          </a-space>

          <a-form-item :field="`title${index}`">
            <a-input
              v-model="question.title"
              placeholder="请输入标题"
              style="width: 100%"
            />
          </a-form-item>

          <a-space
            size="large"
            style="
              margin-bottom: 16px;
              width: 100%;
              display: flex;
              align-items: center;
              justify-content: space-between;
            "
          >
            <h4>题目 {{ index + 1 }} 选项列表</h4>
            <a-button
              size="small"
              @click="addQuestionOption(question, question.options.length)"
            >
              底部添加选项
            </a-button>
          </a-space>

          <div
            style="
              max-height: 300px;
              overflow-y: auto;
              padding-right: 16px;
              background-color: #f9f9f9;
              border-radius: 5px;
            "
          >
            <a-card
              style="
                background-color: #7fd6ec;
                padding: 15px;
                border-radius: 5px;
                margin-bottom: 16px;
              "
            >
              <a-form-item
                v-for="(option, optionIndex) in question.options"
                :key="optionIndex"
                :label="`选项 ${optionIndex + 1}`"
                style="margin-bottom: 16px"
              >
                <a-form-item
                  :field="`key${index}${optionIndex}`"
                  label="选项"
                  style="margin-bottom: 8px"
                >
                  <a-input
                    v-model="option.key"
                    placeholder="请输入选项"
                    style="width: 100%"
                  />
                </a-form-item>
                <a-form-item
                  :field="`value${index}${optionIndex}`"
                  label="选项值"
                  style="margin-bottom: 8px"
                >
                  <a-input
                    v-model="option.value"
                    placeholder="请输入选项值"
                    style="width: 100%"
                  />
                </a-form-item>
                <a-form-item
                  :field="`result${index}${optionIndex}`"
                  label="选项结果"
                  style="margin-bottom: 8px"
                >
                  <a-input
                    v-model="option.result"
                    placeholder="请输入选项结果"
                    style="width: 100%"
                  />
                </a-form-item>
                <a-form-item
                  :field="`score${index}${optionIndex}`"
                  label="选项得分"
                  style="margin-bottom: 8px"
                >
                  <a-input-number
                    v-model="option.score"
                    placeholder="请输入选项得分"
                    style="width: 100%"
                  />
                </a-form-item>
                <a-space
                  size="small"
                  style="width: 100%; display: flex; justify-content: flex-end"
                >
                  <a-button
                    status="danger"
                    @click="deleteQuestionOption(question, optionIndex)"
                    style="margin-bottom: 5px"
                  >
                    删除选项
                  </a-button>
                </a-space>
              </a-form-item>
            </a-card>
          </div>
        </div>
      </a-card>
    </div>
  </div>
  <!-- 提交按钮 -->
  <a-form
    :model="questionContent"
    label-align="left"
    auto-label-width
    @submit="handleSubmit"
  >
    <a-form-item>
      <a-button type="primary" html-type="submit" style="width: 120px">
        提交
      </a-button>
    </a-form-item>
  </a-form>
</template>

<script setup lang="ts">
import { defineProps, ref, watchEffect, withDefaults } from "vue";
import API from "@/api";
import { useRouter } from "vue-router";
import {
  addQuestionUsingPost,
  editQuestionUsingPost,
  listQuestionVoByPageUsingPost,
} from "@/api/questionController";
import message from "@arco-design/web-vue/es/message";
import AiGenterateQuestion from "@/views/add/components/AiGenterateQuestion.vue";

interface Props {
  appId: string;
}

const props = withDefaults(defineProps<Props>(), {
  appId: () => "",
});

const router = useRouter();

// 题目内容结构（理解为题目列表）
const questionContent = ref<API.QuestionContentDTO[]>([]);

/**
 * 添加题目
 * @param index
 */
const addQuestion = (index: number) => {
  questionContent.value.splice(index, 0, {
    title: "",
    options: [],
  });
};

/**
 * 删除题目
 * @param index
 */
const deleteQuestion = (index: number) => {
  questionContent.value.splice(index, 1);
};

/**
 * 添加题目选项
 * @param question
 * @param index
 */
const addQuestionOption = (question: API.QuestionContentDTO, index: number) => {
  if (!question.options) {
    question.options = [];
  }
  question.options.splice(index, 0, {
    key: "",
    value: "",
  });
};

/**
 * 删除题目选项
 * @param question
 * @param index
 */
const deleteQuestionOption = (
  question: API.QuestionContentDTO,
  index: number
) => {
  if (!question.options) {
    question.options = [];
  }
  question.options.splice(index, 1);
};

const oldQuestion = ref<API.QuestionVO>();

/**
 * 加载数据
 */
const loadData = async () => {
  if (!props.appId) {
    return;
  }
  const res = await listQuestionVoByPageUsingPost({
    appId: props.appId as any,
    current: 1,
    pageSize: 1,
    sortField: "createTime",
    sortOrder: "descend",
  });
  if (res.data.code === 0 && res.data.data?.records) {
    oldQuestion.value = res.data.data?.records[0];
    if (oldQuestion.value) {
      questionContent.value = oldQuestion.value.questionContent ?? [];
    }
  } else {
    message.error("获取数据失败，" + res.data.message);
  }
};

// 获取旧数据
watchEffect(() => {
  loadData();
});

/**
 * 提交
 */
const handleSubmit = async () => {
  if (!props.appId || !questionContent.value) {
    return;
  }

  let res: any;
  // 如果是修改
  if (oldQuestion.value?.id) {
    res = await editQuestionUsingPost({
      id: oldQuestion.value.id,
      questionContent: questionContent.value,
    });
  } else {
    // 创建
    res = await addQuestionUsingPost({
      appId: props.appId as any,
      questionContent: questionContent.value,
    });
  }
  if (res.data.code === 0) {
    message.success("操作成功，即将跳转到应用详情页");
    setTimeout(() => {
      router.push(`/app/detail/${props.appId}`);
    }, 3000);
  } else {
    message.error("操作失败，" + res.data.message);
  }
};

// AI 生成题目
const onAiGenerateSuccess = (result: API.QuestionContentDTO[]) => {
  message.success(`AI 生成题目成功，生成：${result.length}题目`);
  questionContent.value = [...questionContent.value, ...result];
};

// AI实时 生成题目
const onAiGenerateSuccessSSE = (result: API.QuestionContentDTO) => {
  questionContent.value = [...questionContent.value, result];
};

/**
 * AI 生成题目
 * @param event
 */
const onSSESatrt = (event: any) => {
  message.success(`AI 生成题目成功，正在生成中...`);
};

/**
 * AI 生成题目成功
 * @param event
 */
const onSSEClose = (event: any) => {
  message.success(`AI 生成题目成功，生成完毕`);
};
</script>

<style scoped>
#addQuestionPage {
  padding: 24px;
}
</style>
